package services;

import java.util.ArrayList;
import java.util.List;

import models.RepositoryFile;
import models.Revision;
import play.modules.gwt.GWTService;
import play.modules.gwt.GWTServicePath;
import client.SearchService;
import client.dtos.RepositoryFileDTO;
import client.dtos.RevisionDTO;

@GWTServicePath("/main/search")
public class SearchServiceImpl extends GWTService implements SearchService {

	public List<String> search(String searchTerm) {
		//find files, for now
		final List<RepositoryFile> findByName = RepositoryFile.findByName(searchTerm);
		final List<String> results = new ArrayList<String>(findByName.size());
		for (final RepositoryFile file : findByName) {
			results.add(file.path);
		}
		return results;
	}

	public List<RepositoryFileDTO> search(final String searchTerm, final boolean searchAnywhere) {
		final List<RepositoryFile> multiFindResults = RepositoryFile.findByPath(searchTerm, searchAnywhere);
		return RepositoryFile.convertToDTOs(multiFindResults);
	}

	public List<RevisionDTO> getMostRecentRevisionForFile(long repositoryFileID, int page) {
		final List<Revision> revision = Revision.getRevisionsForFile(repositoryFileID, page);
		final List<RevisionDTO> dtos = new ArrayList<RevisionDTO>();
		for (Revision r : revision) {
			dtos.add(Revision.convertToDTO(r));
		}
		return dtos;
	}

	public List<RevisionDTO> searchComments(String searchTerm) {
		final List<Revision> revisions = Revision.findByComment(searchTerm);
		return Revision.convertToDTOs(revisions);
	}

	public void hideRepositoryFile(long repositoryFileId) {
		final RepositoryFile rf = RepositoryFile.findById(repositoryFileId);
		rf.hidden = true;
		rf.save();
	}

}
